package org.bukkit.pm.dmatch;

import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageByProjectileEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.entity.EntityDamageEvent;

/**
 * Handle events for all Player related events
 * @author patamau
 */
public class DMatchEntityListener extends EntityListener {
    private final DMatchPlugin _plugin;

    public DMatchEntityListener(DMatchPlugin plugin) {
        _plugin = plugin;
    }
    
    /**
     * Used internally to handle player damage
     * from all possible sources
     */
    private void _checkPlayerDamage(Entity damaged, Entity damager, DamageCause cause, int damage){
    	//only consider player entities, not mobs
    	if(damaged instanceof Player){
    		Player p = (Player)damaged;
			if(damager instanceof Player){
    			//player kill
				Player pk = (Player)damager;
				_plugin.checkDead(p.getName(), pk.getName());
			}else {
				//environment
				_plugin.checkDead(p.getName(), null);
			}
    	}
    }
    
    public void onEntityDeath(EntityDeathEvent event){
    	if(event.getEntity() instanceof Player){
    		Player p = (Player)event.getEntity();
    		_plugin.getDMPlayer(p.getName()).checkHealth();
    	}
    }
    
    public void onEntityDamage(EntityDamageEvent event){
    	_checkPlayerDamage(event.getEntity(),null, event.getCause(), event.getDamage());
    }
    
    public void onEntityDamageByBlock(EntityDamageByBlockEvent event){
    	_checkPlayerDamage(event.getEntity(),null, event.getCause(), event.getDamage());
	}
    
	public void onEntityDamageByEntity(EntityDamageByEntityEvent event){
		_checkPlayerDamage(event.getEntity(),event.getDamager(), event.getCause(), event.getDamage());
	}
	
	public void onEntityDamageByProjectile(EntityDamageByProjectileEvent event){
		_checkPlayerDamage(event.getEntity(),event.getDamager(), event.getCause(), event.getDamage());
	}
}
